package com.apps.ftapp.act;

import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.apps.ftapp.R;
import com.apps.ftapp.activity.BaseActivity;
import com.apps.ftapp.model.SharejlModel;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.SDCardUtils;
import com.apps.ftapp.util.Tools;
import com.arialyy.aria.core.Aria;
import com.google.gson.Gson;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

public class ShareJlDActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.fenxiang_title)
    TextView fenxiangTitle;
    @BindView(R.id.lines)
    TextView lines;
    @BindView(R.id.lesson_img)
    ImageView lessonImg;
    @BindView(R.id.lesson_type)
    TextView lessonType;
    @BindView(R.id.lesson_title)
    TextView lessonTitle;
    @BindView(R.id.lesson_price)
    TextView lessonPrice;
    @BindView(R.id.lesson_fan)
    TextView lessonFan;
    @BindView(R.id.lesson_yongjin)
    TextView lessonYongjin;
    @BindView(R.id.lesson_money)
    TextView lessonMoney;
    @BindView(R.id.fenxinag)
    ImageView fenxinag;
    @BindView(R.id.relzzzz)
    RelativeLayout relzzzz;
    @BindView(R.id.linesss)
    TextView linesss;
    @BindView(R.id.dianji)
    TextView dianji;
    @BindView(R.id.toumai)
    TextView toumai;
    @BindView(R.id.daozhangyongjin)
    TextView daozhangyongjin;
    @BindView(R.id.lkjdsflksjf)
    LinearLayout lkjdsflksjf;
    @BindView(R.id.linessssss)
    TextView linessssss;
    @BindView(R.id.fenxinagtitle)
    TextView fenxinagtitle;
    @BindView(R.id.ppppprice)
    TextView ppppprice;
    @BindView(R.id.weixin)
    TextView weixin;
    @BindView(R.id.pengyouquan)
    TextView pengyouquan;
    @BindView(R.id.qq)
    TextView qq;
    @BindView(R.id.qqkongjian)
    TextView qqkongjian;
    @BindView(R.id.qrcode)
    ImageView qrcode;
    @BindView(R.id.dfkmflkg)
    LinearLayout dfkmflkg;
    @BindView(R.id.baocuntupian)
    TextView baocuntupian;

    private String dirName = SDCardUtils.getSDCardPath() + "iweishhi/";

    private SharejlModel result = new SharejlModel();
    private Gson gson = new Gson();

    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;
    private static final int STORAGE_REQUEST = 1;
    private String temppath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_jl_d);
        ButterKnife.bind(this);
        ShareSDK.initSDK(this);
        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        String id = bundle.getString("id");
        String title = bundle.getString("title");

        weixin.setOnClickListener(this);
        qq.setOnClickListener(this);
        pengyouquan.setOnClickListener(this);
        qingkong.setOnClickListener(this);
        baocuntupian.setOnClickListener(this);

        Aria.download(this).register();


        //显示图片的配置  
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));


        setTitle(title);

        L.i("main", "LLL" + id);

        initView();

        loadData(id);


    }

    /**
     * @param id
     */
    private void loadData(String id) {
        RequestParams params = new RequestParams();
        params.put("inviteId", id);
        Async.post("course/share/detail", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody) + "......");
                    result = gson.fromJson(new String(responseBody), SharejlModel.class);
                    if (Tools.isIntNull(result.getSuccess()) == 1) {


                        fenxiangTitle.setText(result.getSharedetail().getMytitle());
                        lessonTitle.setText(result.getSharedetail().getTitle());
                        lessonPrice.setText("价格：" + result.getSharedetail().getPrice());
                        lessonFan.setText(result.getSharedetail().getFandian());
                        lessonMoney.setText("¥" + result.getSharedetail().getYongjin());


                        dianji.setText(result.getSharedetail().getClick() + "");
                        toumai.setText(result.getSharedetail().getMall() + "");
                        daozhangyongjin.setText("¥" + result.getSharedetail().getYongjin());

                        imageLoader.displayImage(result.getSharedetail().getLargePicture(), lessonImg, options);


                        imageLoader.displayImage(result.getSharedetail().getQrcode(), qrcode, options);

                        ppppprice.setText(result.getSharedetail().getYongjin());

                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }

    private void initView() {


    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.weixin:

                share(0);
                break;

            case R.id.qq:
                share(2);
                break;

            case R.id.pengyouquan:
                share(1);
                break;

            case R.id.qingkong:
                share(3);
                break;

            case R.id.baocuntupian:
                File file = new File(dirName);
                //不存在创建
                if (!file.exists()) {
                    file.mkdir();
                }

                //String DOWNLOAD_URL = DuobeiYunClient.BASE_URL + bean.getRoomId() + ".zip";
//                String DOWNLOAD_URL = dirName+ Tools.getTime()+".png";

                temppath = file.getAbsolutePath();
                if (ContextCompat.checkSelfPermission(ShareJlDActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ShareJlDActivity.this,
                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            STORAGE_REQUEST);

                } else {

                    download(result.getSharedetail().getQrcode(), file.getAbsolutePath());
//                Aria.download(this)
//                        .load(result.getSharedetail().getQrcode())     //读取下载地址
//                        .setDownloadPath(DOWNLOAD_URL) //设置文件保存的完整路径
//                        .start();   //启动下载
                }
                break;
        }
    }


    public void share(int state) {
        OnekeyShare oks = new OnekeyShare();
        oks.disableSSOWhenAuthorize();
        oks.setTitleUrl(result.getSharedetail().getUrl());
        oks.setText(result.getSharedetail().getDesc());
        oks.setImageUrl(result.getSharedetail().getLargePicture());
        oks.setUrl(result.getSharedetail().getUrl());
        oks.setSite(result.getSharedetail().getTitle());
        oks.setSiteUrl(result.getSharedetail().getUrl());
        oks.setTitle(result.getSharedetail().getTitle());
        switch (state) {
            case 0:
//                oks.setTitle("分享到微信");
                oks.setPlatform(Wechat.NAME);
                break;

            case 1:
//                oks.setTitle("分享到朋友圈");
                oks.setPlatform(WechatMoments.NAME);
                break;

            case 2:
//                oks.setTitle("分享到QQ");
                oks.setPlatform(QQ.NAME);
                break;

            case 3:
//                oks.setTitle("分享到QQ空间");
                oks.setPlatform(QZone.NAME);
                break;
        }

        oks.show(ShareJlDActivity.this);


    }


    private void download(String url, String filePath) {
        //判断SDcard是否存在并且可读写
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toasty.normal(getApplicationContext(), "没有权限").show();
            return;
        }

        if ("".equals(Tools.isNull(url))) {

            Toasty.normal(getApplicationContext(), "保存错误").show();
            return;
        }
        L.i("main", url + "___" + url);
        FileDownloader.getImpl().create(url)
                .setPath(filePath)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {

                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Toasty.normal(getApplicationContext(), "保存完成!").show();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Toasty.normal(getApplicationContext(), "保存失败!").show();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == STORAGE_REQUEST) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                download(result.getSharedetail().getQrcode(), temppath);
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
